<?php

namespace app\common\library;

use \Redis as RedisBase;


/**
 * Token操作类
 */
class Redis extends RedisBase
{
    protected $options = [
        'host' => '127.0.0.1',
        'port' => 6379,
        'password' => '',
        'select' => 0,
        'timeout' => 0,
        'persistent' => false,
        'prefix' => '',
    ];

    /** @var Redis $_instance */
    private static $_instance;

    /**
     * 构造函数
     * @param array $options 缓存参数
     * @access public
     */
    public function __construct($options = [])
    {
        parent::__construct();
        if (!extension_loaded('redis')) {
            throw new \BadFunctionCallException('not support: redis');
        }
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        if ($this->options['persistent']) {
            $this->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
        } else {
            $this->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
        }

        if ('' != $this->options['password']) {
            $this->auth($this->options['password']);
        }

        if (0 != $this->options['select']) {
            $this->select($this->options['select']);
        }

        if ('' != $this->options['prefix']) {
            $this->setOption(RedisBase::OPT_PREFIX, $this->options['prefix']);
        }
    }

    /**
     * @param array $options
     * @return Redis
     */
    public static function instance($options = [])
    {
        if (!self::$_instance) {
            self::$_instance = new Redis($options ? $options : config('redis'));
        }
        return self::$_instance;
    }
}
